One of the common text processing tasks is to convert the first letter
of each word in a string to uppercase.
In this task, you are required to apply this transformation.
Input. One string consisting of words written in
lowercase Latin letters (‘a’ – ‘z’). Words are separated by one
or more spaces. The length of the string does not exceed 50 characters.
Output. Print a string identical to the input, but with
the first letter of each word converted to uppercase.
Sample input |
Sample output |
intro to
algo |
Intro To
Algo |
strings
The first
letter of the word can
be identified as follows:
·
If the first character of the string is a letter, it
should be converted to uppercase;
·
If the current character is a letter and there is a
space immediately before it, this character should also be converted to
uppercase;
Algorithm
implementation
Declare a string.
string s;
Read the input string.
getline(cin,s);
If the first character of the string is not a space, it
should be converted to an uppercase letter.
if (s[0] != ' ') s[0] = toupper(s[0]);
If the
current character is a letter and there is a space before it, this character
should also be converted to uppercase.
for(int i = 1; i < s.size(); i++)
if
(s[i] != ' ' && s[i-1] == ' ')
s[i] = toupper(s[i]);
Print the resulting string.
cout << s << endl;
Algorithm
implementation – char array
Declare the char array.
char s[100];
Read the input string.
gets(s);
If the first character of the string is not a space, it
should be converted to an uppercase letter.
if (s[0] != ' ') s[0] = toupper(s[0]);
If the
current character is a letter and there is a space before it, this character
should also be converted to uppercase.
for(i = 1; i < strlen(s); i++)
if
(s[i] != ' ' && s[i-1] == ' ') s[i] = toupper(s[i]);
Print the resulting string.
puts(s);
Java implementation
import java.util.*;
public class Main
{
public static void main(String[] args)
{
Scanner con = new Scanner(System.in);
char s[] = con.nextLine().toCharArray();
if (s[0] != ' ') s[0] = Character.toUpperCase(s[0]);
for(int i = 1; i < s.length; i++)
if (s[i] != ' ' && s[i-1] == ' ')
s[i] = Character.toUpperCase(s[i]);
System.out.println(String.valueOf(s));
con.close();
}
}
Python implementation
Read the input string.
s = input()
The title() function is used to convert
the first letter of each word in a string to uppercase, while the remaining
letters are converted to lowercase.
Print the resulting string.
print(s.title())